import {
  addUserChannelsAPI,
  delUserChannelsAPI,
  getAllChannelsAPI,
  getUserChannelsAPI,
} from '@/api/channel';
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage';
import { Toast } from 'antd-mobile';
import store, { AppDispatch } from '..';
import { ActionType, ChannelItem } from './../reducer/channel';

export const getUserChannelsAction = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      const res = await getUserChannelsAPI();
      dispatch({ type: 'channel/saveUserList', payload: res.data.channels });
      return;
    }

    const localChannels = getLocalChannels();
    if (localChannels.length) {
      dispatch({ type: 'channel/saveUserList', payload: localChannels });
      return;
    }

    const res = await getAllChannelsAPI();
    dispatch({ type: 'channel/saveUserList', payload: res.data.channels.slice(0, 10) });
    setLocalChannels(res.data.channels.slice(0, 10));
  };
};

export const getAllChannelsAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getAllChannelsAPI();
    dispatch({ type: 'channel/saveAllList', payload: res.data.channels });
  };
};

export const addUserChannelAction = (channel: ChannelItem) => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      await addUserChannelsAPI(channel);
    } else {
      const localChannels = getLocalChannels();
      const newList = [...localChannels, channel].sort((a, b) => a.id - b.id);
      setLocalChannels(newList);
    }
    dispatch({ type: 'channel/updateUserList', payload: channel });
    Toast.show({ content: '更新成功' });
  };
};
export const delUserChannelAction = (id: number) => {
  return async (dispatch: AppDispatch, getState: typeof store.getState) => {
    const { userList } = getState().channel;
    if (userList.length <= 5) {
      Toast.show({ content: '至少关注5个频道' });
      return;
    }

    if (id === 0) {
      Toast.show({ content: '不能删除推荐频道' });
      return;
    }

    if (hasToken()) {
      await delUserChannelsAPI(id);
    } else {
      const localChannels = getLocalChannels();
      const newList = localChannels.filter((item) => item.id !== id);
      setLocalChannels(newList);
    }

    dispatch({ type: 'channel/delUserList', payload: id });
    Toast.show({ content: '更新成功' });
  };
};

export const setCurrentIdAction = (id: number): ActionType => ({
  type: 'channel/setCurrentId',
  payload: id,
});
